package com.demo.websocket.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.demo.websocket.domain.*;
import com.demo.websocket.mapper.*;
import com.demo.websocket.service.MedicalKnowledgeService;
import com.demo.websocket.vo.AIAnalysisResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MedicalKnowledgeServiceImpl implements MedicalKnowledgeService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private DiseasesMapper diseasesMapper;

    @Autowired
    private DepartmentDiseasesMapper departmentDiseasesMapper;

    @Autowired
    private SymptomsMapper symptomsMapper;

    @Autowired
    private DepartmentSymptomsMapper departmentSymptomsMapper;
    @Override
    public Dept recommendBestDepartment(AIAnalysisResponse aiResponse) {
        //用于存放科室得分
        Map<Long,Integer> departmentScore = new HashMap<>();
        //1. 根据疾病匹配科室
        aiResponse.getPossibleConditions().forEach(condition -> {
            //1.1 获取疾病
            QueryWrapper<Diseases> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("diseases_name", condition);
            List<Diseases> diseases = diseasesMapper.selectList(queryWrapper);

            //提取疾病ID
            List<Long> diseaseIds = diseases.stream().map(Diseases::getId).collect(Collectors.toList());

            //1.2 获取疾病对应的科室Id
            QueryWrapper<DepartmentDiseases> departmentDiseasesQueryWrapper = new QueryWrapper<>();
            if (diseaseIds.isEmpty()){
                departmentDiseasesMapper.selectList(null);
            }else {
                departmentDiseasesQueryWrapper.in("disease_id", diseaseIds);
                List<DepartmentDiseases> departmentDiseases = departmentDiseasesMapper.selectList(departmentDiseasesQueryWrapper);
                departmentDiseases.forEach(departmentDisease -> {
                    Long departmentId = departmentDisease.getDepartmentId();
                    Integer score = departmentDisease.getMatchWeight();
                    // 改为累加方式：
                    departmentScore.merge(departmentId, score, Integer::sum);
                    log.info("疾病: {}, 科室: {}, 得分: {}", condition, departmentId, score);
                });
            }
        });

        //2.根据症状匹配科室
        String symptomsText = aiResponse.getSymptomAnalysis();
        for (String symptom :extractSymptoms(symptomsText)){
            QueryWrapper<Symptoms> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("name", symptom);
            List<Symptoms> symptoms = symptomsMapper.selectList(queryWrapper);

            //提取症状ID
            List<Long> symptomIds = symptoms.stream().map(Symptoms::getId).collect(Collectors.toList());
            if (symptomIds.isEmpty()){
                departmentSymptomsMapper.selectList(null);
            }else {
                QueryWrapper<DepartmentSymptoms> departmentSymptomsQueryWrapper = new QueryWrapper<>();
                departmentSymptomsQueryWrapper.in("symptom_id", symptomIds);
                List<DepartmentSymptoms> departmentSymptoms = departmentSymptomsMapper.selectList(departmentSymptomsQueryWrapper);
                departmentSymptoms.forEach(departmentSymptom -> {
                    Long departmentId = departmentSymptom.getDepartmentId();
                    Integer score = departmentSymptom.getMatchWeight();
                    // 改为累加方式：
                    departmentScore.merge(departmentId, score, Integer::sum);
                    log.info("症状: {}, 科室: {}, 得分: {}", symptom, departmentId, score);
                });
            }
        }
        //3.根据紧急情况匹配科室
        if("high".equals(aiResponse.getUrgencyLevel())){
            QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("dept_name", "急诊");
            Dept emergencyDept = deptMapper.selectOne(queryWrapper);
            departmentScore.merge(emergencyDept.getId(), 100, Integer::sum);
            log.info("匹配急诊科室: {}", emergencyDept.getDeptName());
        }
        //4.根据科室得分进行排序
        if (departmentScore.isEmpty()){
            QueryWrapper<Dept> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("dept_name", "全科医学科");
            Dept defaultDept = deptMapper.selectOne(queryWrapper);
            log.info("没有匹配的科室，默认选择全科医学科: {}", defaultDept.getDeptName());
            return deptMapper.selectOne(queryWrapper);
        }else {
            return deptMapper.selectOne(new QueryWrapper<Dept>().eq("id", departmentScore.entrySet().stream().max(Map.Entry.comparingByValue()).get().getKey()));
        }

    }

    private List<String> extractSymptoms(String text) {
        // 简单的症状提取逻辑，可以从症状表中匹配
        List<Symptoms> all = symptomsMapper.findAll();
        List<String> commonSymptoms =new ArrayList<>();
        for (Symptoms symptom : all) {
            commonSymptoms.add(symptom.getName());
        }
        return commonSymptoms.stream()
                .filter(text::contains)
                .collect(Collectors.toList());
    }
}
